package com.jack.online.study.controller.oss;


import com.jack.online.study.common.base.result.R;
import com.jack.online.study.common.base.result.ResultCodeEnum;
import com.jack.online.study.common.exception.GuliException;
import com.jack.online.study.common.util.ExceptionUtils;
import com.jack.online.study.service.oss.FileService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@CrossOrigin //跨域
@RestController
@RequestMapping("/admin/oss/file")
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    /**
     * 文件上传
     * @param file
     */

    @PostMapping("upload")
    public R upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("module") String module) throws IOException {
        try {
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            String uploadUrl = fileService.upload(bytes, module, originalFilename);

            //返回r对象
            return R.ok().message("文件上传成功").data("url", uploadUrl);
        } catch (IOException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }
    @GetMapping("/getImage/{id}/{fileName}")
    public ResponseEntity<Object> getImage(@PathVariable("id") Long id,
                                           @PathVariable("fileName") String fileName) {

        return fileService.getImage(id, fileName);
    }


    @DeleteMapping("remove")
    public R removeFile(
            @RequestBody String url) {

        fileService.removeFile(url);
        return R.ok().message("文件刪除成功");
    }

    @GetMapping("test")
    public R test() {
        log.info("oss test被调用");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return R.ok();
    }
}